<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-6xl mx-auto space-y-8">
      <!-- 操作说明 -->
      <InstructionsCard :instructions="instructions" />

      <!-- 表单属性配置 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <i class="ri-settings-3-line h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">表单属性</h2>
        </div>
        
        <div class="grid grid-cols-2 gap-6">
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">表单名称</label>
            <input 
              v-model="formConfig.name"
              type="text"
              class="w-full px-4 py-2 border rounded-lg"
              placeholder="输入表单名称"
            />
          </div>
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">表单标题</label>
            <input 
              v-model="formConfig.text"
              type="text"
              class="w-full px-4 py-2 border rounded-lg"
              placeholder="输入表单标题"
            />
          </div>
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">网格宽度</label>
            <input 
              v-model.number="formConfig.gridWidth"
              type="number"
              class="w-full px-4 py-2 border rounded-lg"
            />
          </div>
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">网格高度</label>
            <input 
              v-model.number="formConfig.gridHeight"
              type="number"
              class="w-full px-4 py-2 border rounded-lg"
            />
          </div>
        </div>
      </div>

      <!-- 控件工具箱 - 移到顶部 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center justify-between mb-6">
          <div class="flex items-center">
            <div class="p-2 bg-blue-50 rounded-lg">
              <i class="ri-tools-line h-6 w-6 text-blue-500" />
            </div>
            <h2 class="text-xl font-semibold text-gray-800 ml-3">控件工具箱</h2>
          </div>
        </div>
        
        <div class="flex flex-wrap gap-4">
          <div
            v-for="widget in availableWidgets"
            :key="widget.type"
            class="widget-item px-4 py-2 bg-gray-50 rounded-lg cursor-move hover:bg-gray-100 transition-colors"
            draggable="true"
            @dragstart="dragStart($event, widget)"
          >
            <i :class="[widget.icon, 'mr-2']"></i>
            {{ widget.label }}
          </div>
        </div>
      </div>

      <!-- 设计区域 -->
      <div class="bg-white rounded-xl shadow-sm p-6 mt-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <i class="ri-layout-line h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">设计区域</h2>
          
          <!-- 网格控制按钮 -->
          <div class="ml-auto flex gap-3">
            <button
              class="inline-flex items-center px-4 py-2 text-sm font-medium text-gray-600 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors duration-200"
              @click="toggleGrid"
            >
              <i class="ri-grid-line mr-2 text-lg"></i>
              {{ showGrid ? '隐藏网格' : '显示网格' }}
            </button>
            <button
              class="inline-flex items-center px-4 py-2 text-sm font-medium text-gray-600 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors duration-200"
              @click="toggleSnap"
            >
              <i class="ri-magnet-line mr-2 text-lg"></i>
              {{ snapToGrid ? '关闭对齐' : '开启对齐' }}
            </button>
          </div>
        </div>
        
        <div class="flex gap-4">
          <!-- 左侧控件工具箱 -->
          <div class="w-48 bg-gray-50 p-4 rounded-lg">
            <div class="widget-item mb-2 p-2 bg-white rounded cursor-move hover:bg-gray-100"
                 v-for="widget in availableWidgets"
                 :key="widget.type"
                 draggable="true"
                 @dragstart="dragStart($event, widget)">
              <i :class="[widget.icon, 'mr-2']"></i>
              {{ widget.label }}
            </div>
          </div>

          <!-- 右侧设计区域 -->
          <div 
            class="design-area flex-1 border rounded-lg relative mt-4"
            :class="{ 'show-grid': showGrid, 'dragover': draggedWidget }"
            :style="{
              width: `${formConfig.gridWidth * 10}px`,
              height: `${formConfig.gridHeight * 10}px`,
              backgroundSize: '10px 10px'
            }"
            @dragover.prevent
            @drop="handleDrop"
          >
            <div
              v-for="(widget, index) in widgets"
              :key="widget.id"
              class="widget absolute border rounded p-2 cursor-move"
              :class="[
                widget.type,
                { selected: selectedWidget === index }
              ]"
              :style="{
                left: `${widget.posX * 10}px`,
                top: `${widget.posY * 10}px`,
                width: `${widget.gridWidth * 10}px`,
                height: `${widget.gridHeight * 10}px`,
                zIndex: selectedWidget === index ? 100 : 1
              }"
              draggable="true"
              @dragstart="dragStartWidget($event, index)"
              @dragend="dragEndWidget"
              @click.stop="selectWidget(index)"
            >
              <div class="widget-content">
                {{ widget.name || `${widget.type}${index + 1}` }}
              </div>
              <!-- 调整大小的手柄 -->
              <div v-if="selectedWidget === index" class="resize-handles">
                <div
                  v-for="handle in resizeHandles"
                  :key="handle.position"
                  class="resize-handle"
                  :class="handle.position"
                  @mousedown.stop="startResize($event, handle.position)"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 属性编辑器 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <i class="ri-edit-2-line h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">属性编辑器</h2>
        </div>
        
        <div v-if="selectedWidget !== null">
          <div class="grid grid-cols-2 gap-6">
            <div class="form-group">
              <label class="block text-sm font-medium text-gray-700 mb-2">控件名称</label>
              <input 
                v-model="widgets[selectedWidget].name"
                type="text"
                class="w-full px-4 py-2 border rounded-lg"
              />
            </div>
            <!-- 其他属性编辑字段 -->
          </div>
        </div>
        <div v-else class="text-gray-500 text-center py-4">
          请选择一个控件进行编辑
        </div>
      </div>

      <!-- 生成代码按钮 -->
      <div class="flex justify-center gap-4">
        <button 
          @click="generateXml"
          class="inline-flex items-center px-6 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
        >
          <i class="ri-code-box-line mr-2 text-lg"></i>
          生成4FD文件
        </button>
        <button 
          @click="previewForm"
          class="inline-flex items-center px-6 py-2 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors duration-200"
        >
          <i class="ri-eye-line mr-2 text-lg"></i>
          预览表单
        </button>
      </div>

      <!-- 生成的代码预览 -->
      <GeneratedCode 
        v-if="isVisible && generatedCode" 
        :code-content="generatedCode" 
        :is-visible="isVisible"
        @copy-success="handleCopySuccess"
        @copy-error="handleCopyError"
      />
    </div>
  </div>
</template> 

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import GeneratedCode from '../common/GeneratedCode.vue';
import InstructionsCard from '../common/InstructionsCard.vue';
import instructions from '@/assets/form-designer-instructions.md';

// 表单配置
const formConfig = reactive({
  name: 'Form',
  text: 'Form',
  gridWidth: 169,
  gridHeight: 29
});

// 可用控件列表
const availableWidgets = [
  {
    type: 'table',
    label: '表格',
    icon: 'ri-table-line',
    defaultProps: {
      name: 'Table1',
      gridWidth: 20,
      gridHeight: 10,
      totalRows: 5,
      posX: 0,
      posY: 0
    }
  },
  {
    type: 'edit',
    label: '编辑框',
    icon: 'ri-edit-box-line',
    defaultProps: {
      name: 'Edit1',
      gridWidth: 6,
      gridHeight: 1,
      title: 'Edit1',
      posX: 0,
      posY: 0
    }
  },
  {
    type: 'button',
    label: '按钮',
    icon: 'ri-checkbox-blank-line',
    defaultProps: {
      name: 'Button1',
      gridWidth: 4,
      gridHeight: 1,
      text: 'Button1',
      posX: 0,
      posY: 0
    }
  },
  {
    type: 'label',
    label: '标签',
    icon: 'ri-text',
    defaultProps: {
      name: 'Label1',
      gridWidth: 4,
      gridHeight: 1,
      text: 'Label1',
      posX: 0,
      posY: 0
    }
  }
];

// 控件列表
const widgets = ref([]);
// 当前选中的控件索引
const selectedWidget = ref(null);
// 生成的代码相关
const isVisible = ref(false);
const generatedCode = ref('');

// 网格和对齐相关状态
const showGrid = ref(true);
const snapToGrid = ref(true);

// 调整大小相关状态
const isResizing = ref(false);
const resizeStartPos = reactive({ x: 0, y: 0 });
const resizeStartSize = reactive({ width: 0, height: 0 });
const resizeHandles = [
  { position: 'top-left' },
  { position: 'top-right' },
  { position: 'bottom-left' },
  { position: 'bottom-right' }
];

// 拖拽相关状态
const draggedWidget = ref(null);

// 拖拽开始 - 从工具箱
const dragStart = (event, widget) => {
  draggedWidget.value = { ...widget.defaultProps, type: widget.type };
  event.dataTransfer.effectAllowed = 'copy';
};

// 拖拽开始 - 已有控件
const dragStartWidget = (event, index) => {
  draggedWidget.value = { ...widgets.value[index], moving: true };
  event.dataTransfer.effectAllowed = 'move';
};

// 拖拽结束
const dragEndWidget = () => {
  draggedWidget.value = null;
};

// 处理放置
const handleDrop = (event) => {
  event.preventDefault();
  
  if (!draggedWidget.value) return;

  const rect = event.currentTarget.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  // 计算网格位置，并确保在边界内
  const gridX = Math.min(
    Math.max(0, Math.floor(x / 10)),
    formConfig.gridWidth - draggedWidget.value.gridWidth
  );
  const gridY = Math.min(
    Math.max(0, Math.floor(y / 10)),
    formConfig.gridHeight - draggedWidget.value.gridHeight
  );

  if (draggedWidget.value.moving) {
    // 移动现有控件
    const index = widgets.value.findIndex(w => w.id === draggedWidget.value.id);
    if (index !== -1) {
      widgets.value[index].posX = gridX;
      widgets.value[index].posY = gridY;
    }
  } else {
    // 添加新控件
    const newWidget = {
      ...draggedWidget.value,
      id: `widget_${Date.now()}`,
      posX: gridX,
      posY: gridY,
      name: `${draggedWidget.value.type}${widgets.value.length + 1}`
    };
    widgets.value.push(newWidget);
    selectedWidget.value = widgets.value.length - 1;
  }

  draggedWidget.value = null;
};

// 网格和对齐控制
const toggleGrid = () => showGrid.value = !showGrid.value;
const toggleSnap = () => snapToGrid.value = !snapToGrid.value;



// 调整大小处理
const startResize = (event, position) => {
  isResizing.value = true;
  const targetWidget = widgets.value[selectedWidget.value];
  
  resizeStartPos.x = event.clientX;
  resizeStartPos.y = event.clientY;
  resizeStartSize.width = targetWidget.gridWidth;
  resizeStartSize.height = targetWidget.gridHeight;
  
  const resizeDirection = {
    'top-left': { x: -1, y: -1 },
    'top-right': { x: 1, y: -1 },
    'bottom-left': { x: -1, y: 1 },
    'bottom-right': { x: 1, y: 1 }
  }[position];

  const handleResizeMove = (e) => {
    if (!isResizing.value) return;
    
    const deltaX = (e.clientX - resizeStartPos.x) * resizeDirection.x;
    const deltaY = (e.clientY - resizeStartPos.y) * resizeDirection.y;
    
    if (targetWidget) {
      const newWidth = Math.max(1, Math.round((resizeStartSize.width * 10 + deltaX) / 10));
      const newHeight = Math.max(1, Math.round((resizeStartSize.height * 10 + deltaY) / 10));
      
      targetWidget.gridWidth = newWidth;
      targetWidget.gridHeight = newHeight;

      if (resizeDirection.x < 0) {
        targetWidget.posX = Math.round(targetWidget.posX - (newWidth - resizeStartSize.width));
      }
      if (resizeDirection.y < 0) {
        targetWidget.posY = Math.round(targetWidget.posY - (newHeight - resizeStartSize.height));
      }
    }
  };

  document.addEventListener('mousemove', handleResizeMove);
  document.addEventListener('mouseup', () => {
    isResizing.value = false;
    document.removeEventListener('mousemove', handleResizeMove);
  }, { once: true });
};

// 选择控件
const selectWidget = (index) => {
  selectedWidget.value = index;
};

// 生成XML代码
const generateXml = () => {
  let xml = '<?xml version="1.0" encoding="UTF-8" ?>\n';
  xml += `<ManagedForm gstVersion="22800" name="ManagedForm">\n`;
  xml += '  <AGSettings/>\n';
  
  // 生成Record部分
  xml += '  <Record additionalTables="" joinLeft="" joinOperator="" joinRight="" name="Record1" order="" where=""/>\n';
  
  // 如果有编辑框，生成Record2
  const editWidgets = widgets.value.filter(w => w.type === 'edit');
  if (editWidgets.length > 0) {
    xml += '  <Record additionalTables="" joinLeft="" joinOperator="" joinRight="" name="Record2" order="" where="">\n';
    editWidgets.forEach(widget => {
      xml += `    <RecordField colName="" fieldIdRef="${widget.fieldId}" name="${widget.name}" sqlTabName="" table_alias_name=""/>\n`;
    });
    xml += '  </Record>\n';
  }
  
  // 生成Form部分
  xml += `  <Form gridHeight="${formConfig.gridHeight}" gridWidth="${formConfig.gridWidth}" name="${formConfig.name}" text="${formConfig.text}">\n`;
  
  // 生成控件
  widgets.value.forEach(widget => {
    if (widget.type === 'table') {
      xml += `    <Table gridHeight="${widget.gridHeight}" gridWidth="${widget.gridWidth}" name="${widget.name}" posX="${widget.posX}" posY="${widget.posY}" totalRows="${widget.totalRows}">\n`;
      // 如果表格内有其他控件，生成它们
      const tableWidgets = widgets.value.filter(w => w.parentId === widget.id);
      tableWidgets.forEach(childWidget => {
        xml += `      <${childWidget.type} aggregateColName="" aggregateName="" aggregateTableAliasName="" aggregateTableName="" colName="" columnCount="" fieldId="${childWidget.fieldId}" gridHeight="${childWidget.gridHeight}" gridWidth="${childWidget.gridWidth}" name="${childWidget.name}" posX="${childWidget.posX}" posY="${childWidget.posY}" rowCount="" sqlTabName="" stepX="" stepY="" tabIndex="${childWidget.fieldId}" table_alias_name="" title="${childWidget.title}" widget="${childWidget.type}"/>\n`;
      });
      xml += '    </Table>\n';
    }
  });
  
  xml += '  </Form>\n';
  
  // 生成DiagramLayout部分
  xml += '  <DiagramLayout>\n';
  xml += '    <![CDATA[]]>\n';
  xml += '  </DiagramLayout>\n';
  xml += '</ManagedForm>';
  
  generatedCode.value = xml;
  isVisible.value = true;
};

// 预览表单
const previewForm = () => {
  ElMessage.info('预览功能开发中...');
};

// 复制成功处理
const handleCopySuccess = () => {
  ElMessage.success('代码已成功复制到剪贴板');
};

// 复制失败处理
const handleCopyError = () => {
  ElMessage.error('复制失败，请���动复制代码');
};
</script> 

<style scoped>
.design-area {
  background-color: white;
  background-image: none;
}

.design-area.show-grid {
  background-image: 
    linear-gradient(to right, rgba(229, 231, 235, 0.3) 1px, transparent 1px),
    linear-gradient(to bottom, rgba(229, 231, 235, 0.3) 1px, transparent 1px);
}

.design-area.dragover {
  border-color: #3b82f6;
  background-color: rgba(59, 130, 246, 0.05);
}

.widget {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 0.25rem;
  cursor: move;
  user-select: none;
  transition: all 0.2s;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.widget:hover {
  border-color: #3b82f6;
}

.widget.selected {
  border: 2px solid #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.resize-handles {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.resize-handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background: white;
  border: 2px solid #3b82f6;
  border-radius: 50%;
}

.resize-handle.top-left { top: -4px; left: -4px; cursor: nw-resize; }
.resize-handle.top-right { top: -4px; right: -4px; cursor: ne-resize; }
.resize-handle.bottom-left { bottom: -4px; left: -4px; cursor: sw-resize; }
.resize-handle.bottom-right { bottom: -4px; right: -4px; cursor: se-resize; }

.widget-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.875rem;
  color: #374151;
}

.widget-item {
  display: inline-flex;
  align-items: center;
  font-size: 0.875rem;
  transition: all 0.2s;
}

.widget-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.design-area-content {
  width: 100%;
  height: 100%;
  position: relative;
}
</style> 